import axios, {AxiosRequestConfig} from 'axios';
import {message} from 'antd';
import {useNavigate} from "react-router-dom";
// Full config:  https://github.com/axios/axios#request-config
// axios.defaults.baseURL = process.env.baseURL || process.env.apiUrl || '';
// axios.defaults.headers.common['Authorization'] = AUTH_TOKEN;
// axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';

let config: AxiosRequestConfig;
config = {
    // baseURL: process.env.baseURL || process.env.apiUrl || ""
    timeout: 30 * 1000, // Timeout
    withCredentials: true, // Check cross-site Access-Control
    // 请求头
    headers: {
        'X-Requested-With': 'XMLHttpRequest',
        'Content-Type': 'application/json',
    },
};

const toLogin = () => {
    // react-router6中的编程式路由导航
    const navigate = useNavigate()
    // 跳转到用户登录页面
    navigate('/login')
    //
}

//  返回类型 <T = any, R = AxiosResponse<T>, D = any>(url: string, config?: AxiosRequestConfig<D>): Promise<R>;
const _axios = axios.create(config);
// 设置请求拦截器, 后设置先执行
_axios.interceptors.request.use(
    function (config) {
        // Do something before request is sent
        return config;
    },
    function (error) {
        // Do something with request error
        return Promise.reject(error);
    }
);

// 设置响应拦截器
_axios.interceptors.response.use(
     function (response) {
        // Do something with response data
        return response.data;
    },
    function (error)  {
        // Do something with response error
        if(error.response.status){
            switch (error.response.status){
                case 401:
                    // 未登录
                    message.error('用户未登录', 1000, toLogin).then()
                    break;
                case 403:
                    // 登录过期
                    message.error('登录过期,请重新登录', 1000, toLogin)
                    break;
                case 404:
                    // 请求资源不存在
                    message.error('请求资源不存在', 1000)
                    break;
                case 500:
                    // 服务器出错
                    message.error('服务器错误,稍后重试', 1000)
                    break;
                default:
                    // 返回
                    message.error(error.response.data.message, 1000)
            }
        }
        return Promise.reject(error);
    }
);

export default _axios;
